package com.lin.util.pdfutil;

import com.spire.pdf.PdfDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * pdf转图片工具
 *
 * @author 九分石人
 */
@Slf4j
public class PdfToPicUtil {

    /**
     * pdf转图片
     * 遍历pdf每一页都生成一个图片
     *
     * @param inputStream 将pdf以流的方式传进来传进来
     * @return 返会图片的流的集合
     */
    public static List<ByteArrayOutputStream> pdfToPic1(InputStream inputStream) {
        String imageType = "jpg";
        List<ByteArrayOutputStream> outputStreamList = new ArrayList<>();
        try {
            PDDocument pdDocument = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int numberOfPages = pdDocument.getNumberOfPages();
            for (int i = 0; i < numberOfPages; i++) {
                ByteArrayOutputStream temp = new ByteArrayOutputStream();
                BufferedImage image = renderer.renderImageWithDPI(i, 90);
                ImageIO.write(image, imageType, temp);
                outputStreamList.add(temp);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return outputStreamList;
    }

    /**
     * pdf转图片,仅支持png格式格式
     *
     * @param inputStream 将pdf以流的方式传进来传进来
     * @return 返会图片的流的集合
     */
    public static List<ByteArrayOutputStream> pdfToPic2(InputStream inputStream) {
        List<ByteArrayOutputStream> outputStreamList = new ArrayList<>();
        try {
            //加载PDF文件
            PdfDocument pdfDocument = new PdfDocument();
            pdfDocument.loadFromStream(inputStream);
            BufferedImage image;
            //保存PDF的每一页到图片
            for (int i = 0; i < pdfDocument.getPages().getCount(); i++) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                image = pdfDocument.saveAsImage(i);
                ImageIO.write(image, "PNG", byteArrayOutputStream);
                outputStreamList.add(byteArrayOutputStream);
            }
            pdfDocument.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return outputStreamList;
    }


}
